import json
import time

# 原始数据
with open('devices.json', 'r') as file:
    data = json.load(file)

# 获取当前时间戳并转换为整数，去除小数部分
current_timestamp = str(int(time.time()))

# 生成的目标JSON对象列表
json_objects = []

for index, item in enumerate(data):
    # 解析IP和端口
    ip_port = item[1].split(':')
    host = ip_port[0]
    port = ip_port[1]
    name = item[3]  # 使用第四个字段作为name
    
    # 创建基于时间戳和序号递增的ID
    id_str = f"{current_timestamp}{index + 1:03d}"  # 时间戳后加上三位数的序号
    
    if item[0] == 'MODBUSTCP':
        obj = {
            "id": "modbus_"+name,
            "type": "modbus-client",
            "name": name,
            "clienttype": "tcp",
            "bufferCommands": True,
            "stateLogEnabled": False,
            "queueLogEnabled": False,
            "failureLogEnabled": True,
            "tcpHost": host,
            "tcpPort": port,
            "tcpType": "DEFAULT",
            "serialPort": "/dev/ttyUSB",  # 这些字段可能不需要，但为了匹配格式保留
            "serialType": "RTU-BUFFERD",
            "serialBaudrate": "9600",
            "serialDatabits": "8",
            "serialStopbits": "1",
            "serialParity": "none",
            "serialConnectionDelay": "100",
            "serialAsciiResponseStartDelimiter": "0x3A",
            "unit_id": 1,
            "commandDelay": 1,
            "clientTimeout": 1000,
            "reconnectOnTimeout": True,
            "reconnectTimeout": 2000,
            "parallelUnitIdsAllowed": True,
            "showErrors": False,
            "showWarnings": True,
            "showLogs": True
        }
        json_objects.append(obj)
    elif item[0] == 'MYSQL':
        obj = {
            "id": id_str,
            "type": "MySQLdatabase",
            "name": name,
            "host": host,
            "port": port,
            "db": item[3],  # 使用第四个字段作为数据库名
            "tz": "",
            "charset": "UTF8"
        }
        json_objects.append(obj)
    elif item[0] == 'INFLUXDB':
        obj = {
            "id": id_str,
            "type": "influxdb",
            "hostname": host,
            "port": port,
            "protocol": "http",
            "database": item[3],  # 使用第四个字段作为数据库名
            "name": name,
            "usetls": False,
            "tls": "",
            "influxdbVersion": "1.x",
            "url": f"http://{host}:{port}",
            "timeout": "10",
            "rejectUnauthorized": True
        }
        json_objects.append(obj)

# 输出结果为JSON格式并保存到文件
output_file_path = '../config-nodes.json'
with open(output_file_path, 'w', encoding='utf-8') as f:
    json.dump(json_objects, f, ensure_ascii=False, indent=4)

print(f"配置已保存到 {output_file_path}")